<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane v-loading="loading" label="用户管理" name="first">
            <el-button type="primary" size="small" @click="dialogFormVisible = true">+ 新增角色</el-button>
            <el-table
              :data="rows"
              style="width: 100%;margin:20px"
            >
              <el-table-column
                :index="indexMethod"
                type="index"
                prop="date"
                label="序号"
                width="180"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                label="操作"
              >
                <template #default="{row}">
                  <el-button type="text" size="small" @click="clickAssignPower(row.id)">分配权限</el-button>
                  <el-button type="text" size="small" @click="delRole(row.id)">删除</el-button>
                  <el-button type="text" size="small" @click="edit(row.id)">修改</el-button>
                </template>

              </el-table-column>
            </el-table>
            <!--
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
               -->
            <!-- 每页显示条目个数，支持 .sync 修饰符 -->

            <el-pagination
              :current-page="page"
              :page-sizes="[1, 2, 3, 4]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="true"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>

      <el-dialog :title="showTitle" :visible="dialogFormVisible" @close="close">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="角色名称" label-width="13%" prop="name">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色描述" label-width="13%" prop="description">
            <el-input v-model="form.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submitAddRole">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 分配权限弹窗 -->
      <el-dialog title="分配权限" :visible="dialogPowerVisible" @close="closePower" @open="openDialogPower">
        <el-tree ref="tree" :data="treeList" :props="{label:'name'}" default-expand-all show-checkbox check-strictly node-key="id" />
        <template #footer>
          <el-button @click="closePower">取 消</el-button>
          <el-button type="primary" @click="submitPower">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { reqGetCompanyById } from '@/api/company'
import { reqAddRole, reqAllRoleList, reqAssignPerm, reqDelRole, reqGetRoleDetail, reqUpdateRoleDetail } from '@/api/setting'
import { reqGetPermissionList } from '@/api/permission'
import { listToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'first',
      page: 1,
      pagesize: 2,
      total: 0,
      rows: null,
      loading: false,
      form: {
        name: '',
        description: ''
      },
      companyForm: {},
      dialogFormVisible: false,
      rules: {
        name: [
          { required: true, message: '角色名称为必填', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述为必填', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      },
      dialogPowerVisible: false,
      roleIds: '',
      treeList: []

    }
  },
  computed: {

    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    console.log('我的信息', this.userInfo)
    this.allRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getCompanyInfo() {
      const data = await reqGetCompanyById(this.$store.state.user.userInfo.companyId)
      this.companyForm = data
      console.log('company', data)
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    async allRoleList() {
      this.loading = true
      const { total, rows } = await reqAllRoleList(this.page, this.pagesize)
      this.total = total
      this.rows = rows
      this.loading = false
    },
    handleCurrentChange(val) {
      this.page = val
      this.allRoleList()
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.allRoleList()
    },
    async close() {
      this.dialogFormVisible = false
      await this.$nextTick()
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    closePower() {
      this.dialogPowerVisible = false
    },
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    async delRole(id) {
      await reqDelRole(id)
      if (this.rows.length === 1) {
        this.page--
      }
      this.allRoleList()
    },
    async submitAddRole() {
      try {
        await this.$refs['form'].validate()
      } catch {
        return this.$message.error('校验没通过')
      }
      if (this.form.id) {
        await reqUpdateRoleDetail(this.form)
      } else {
        await reqAddRole(this.form)
        // this.page = Math.ceil((this.total + 1) / this.pagesize)
        this.page = Math.ceil(++this.total / this.pagesize)

        // this.handleCurrentChange(this.page)
      }

      this.allRoleList()
      this.dialogFormVisible = false
    },
    async submitPower() {
      await reqAssignPerm({
        id: this.roleIds,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.dialogPowerVisible = false
      this.$refs.tree.setCheckedKeys([])
      this.$message.success('分配成功')
    },
    async edit(id) {
      this.dialogFormVisible = true
      const res = await reqGetRoleDetail(id)
      this.form = res
    },
    clickAssignPower(id) {
      this.roleIds = id
      this.dialogPowerVisible = true
    },
    async openDialogPower() {
      const res = await reqGetPermissionList()
      this.treeList = listToTree(res, '0')
      // 获取角色详情
      const reqGetRoleDetail1 = await reqGetRoleDetail(this.roleIds)
      this.$refs.tree.setCheckedKeys(reqGetRoleDetail1.permIds)
    }
  }
}
</script>

<style>

</style>
